﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Xml;
using SocialFront.Providers.Media;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic.web;
using umbraco.presentation.nodeFactory;
using apiBll = umbraco.BusinessLogic;
using apiRelation = umbraco.cms.businesslogic.relation;

namespace SocialFront.Provider.Umbraco
{
    public class UmbracoMedia : MediaBase
    {
        public override Entities.Media UploadMedia(FileUpload fileUpload, string location)
        {
            return SaveUploadedFile(fileUpload, Convert.ToInt32(location));
        }

        public override Entities.Media GetMediaById(int id)
        {
            return ConvertNodeToMedia(new Media(id));
        }

        private Entities.Media SaveUploadedFile(FileUpload uploadControl, int mediaFolderAliasId)
        {
            string _text = "";
            Media m = null;
            Entities.Media eMedia = null;
            if (uploadControl.PostedFile != null)
            {
                if (uploadControl.PostedFile.FileName != "")
                {
                    // Find filename
                    _text = uploadControl.PostedFile.FileName;

                    string filename = _text.Substring(_text.LastIndexOf("\\") + 1, _text.Length - _text.LastIndexOf("\\") - 1).ToLower();

                    // create the Media Node
                    // TODO:  get parent id for current category - as selected by user (see below)
                    // - for now just stick these in the media root :: node = -1
                    m = Media.MakeNew(
                        filename, MediaType.GetByAlias("image"), User.GetUser(0), mediaFolderAliasId);

                    // Create a new folder in the /media folder with the name /media/propertyid
                    string mediaRootPath = "/media/"; // This should be refactored so the upload location can be speficied in the web.config
                    string storagePath = HttpContext.Current.Request.PhysicalApplicationPath + mediaRootPath + m.Id.ToString();
                    System.IO.Directory.CreateDirectory(storagePath);
                    string _fullFilePath = storagePath + "\\" + filename;
                    uploadControl.PostedFile.SaveAs(_fullFilePath);

                    // Save extension
                    string orgExt = ((string)_text.Substring(_text.LastIndexOf(".") + 1, _text.Length - _text.LastIndexOf(".") - 1));
                    orgExt = orgExt.ToLower();
                    string ext = orgExt.ToLower();
                    try
                    {
                        m.getProperty("umbracoExtension").Value = ext;
                    }
                    catch { }

                    // Save file size
                    try
                    {
                        FileInfo fi = new FileInfo(_fullFilePath);
                        m.getProperty("umbracoBytes").Value = fi.Length.ToString();
                    }
                    catch { }

                    // Check if image and then get sizes, make thumb and update database
                    if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + ext + ",") > 0)
                    {
                        int fileWidth;
                        int fileHeight;

                        FileStream fs = new FileStream(_fullFilePath,
                            FileMode.Open, FileAccess.Read, FileShare.Read);

                        System.Drawing.Image image = System.Drawing.Image.FromStream(fs);
                        fileWidth = image.Width;
                        fileHeight = image.Height;
                        fs.Close();
                        try
                        {
                            m.getProperty("umbracoWidth").Value = fileWidth.ToString();
                            m.getProperty("umbracoHeight").Value = fileHeight.ToString();
                        }
                        catch
                        {
                            // Add logging of errors to the umbraco database.
                            //umbraco
                        }

                        // Generate thumbnails
                        //string fileNameThumb = _fullFilePath.Replace("." + orgExt, "_thumb");
                        //generateThumbnail(image, 100, fileWidth, fileHeight, _fullFilePath, ext, fileNameThumb + ".jpg");

                        image.Dispose();
                    }
                    string mediaPath = "/media/" + m.Id.ToString() + "/" + filename;

                    m.getProperty("umbracoFile").Value = mediaPath;
                    m.XmlGenerate(new XmlDocument());

                    eMedia = ConvertNodeToMedia(m);
                }
            }
            // return the media...
            return eMedia;
        }

        private Entities.Media ConvertNodeToMedia(Media media)
        {
            Entities.Media eMedia = new Entities.Media();

            eMedia.Id = media.Id;
            eMedia.Name = media.Text;
            eMedia.Width = Convert.ToInt32(media.getProperty("umbracoWidth").Value);
            eMedia.Height = Convert.ToInt32(media.getProperty("umbracoHeight").Value);
            eMedia.FilePath = media.getProperty("umbracoFile").Value.ToString();
            eMedia.FileSize = media.getProperty("umbracoBytes").Value.ToString();
            eMedia.Extension = media.getProperty("umbracoExtension").Value.ToString();
            
            return eMedia;
        }
    }
}
